package com.bida.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bida.constant.StatusConstant;
import com.bida.context.BaseContext;
import com.bida.domain.dto.DishDTO;
import com.bida.domain.dto.DishPageQueryDTO;
import com.bida.domain.po.*;
import com.bida.domain.vo.DishVO;
import com.bida.exception.BaseException;
import com.bida.mapper.DishFlavorMapper;
import com.bida.mapper.DishMapper;
import com.bida.mapper.SetmealDishMapper;
import com.bida.mapper.SetmealMapper;
import com.bida.result.PageResult;
import com.bida.result.Result;
import com.bida.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.bida.constant.MessageConstant.*;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024-09-06
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private ISetmealDishService setmealDishService;

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private ICategoryService categoryService;



    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> getDishInfoPage(DishPageQueryDTO dishPageQueryDTO) {
     int page = dishPageQueryDTO.getPage();
     int pageSize = dishPageQueryDTO.getPageSize();
     String name = dishPageQueryDTO.getName();
     Integer categoryId = dishPageQueryDTO.getCategoryId();
     Integer status = dishPageQueryDTO.getStatus();

        IPage<Dish> nowPage = new Page<>(page, pageSize);
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(name)){
            queryWrapper.like("name",name);
        }
        if (categoryId != null){
            queryWrapper.eq("category_id",categoryId);
        }
        if (status != null){
            queryWrapper.eq("status",status);
        }
        queryWrapper.orderByDesc("update_time");

        IPage<Dish> dishIPage = this.page(nowPage, queryWrapper);
        PageResult pageResult = new PageResult();
        pageResult.setRecords(dishIPage.getRecords());
        pageResult.setTotal(dishIPage.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @Override
    public Result insertDishInfo(DishDTO dishDTO) {
        // 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateUser(userId);
        dish.setCreateUser(userId);
        // 判断菜品是否存在
        Dish existDish = this.lambdaQuery()
                .eq(Dish::getName, dish.getName())
                .eq(Dish::getCategoryId, dish.getCategoryId())
                .one();
        if (existDish != null){
            throw new BaseException(DISH_IS_EXIST);
        }
        // 新增菜品
        this.save(dish);
        Long dishId = this.lambdaQuery()
                .eq(Dish::getName, dish.getName())
                .eq(Dish::getCategoryId, dish.getCategoryId())
                .one()
                .getId();
        // 新增口味
        for (DishFlavor flavor : dishDTO.getFlavors()) {
            DishFlavor dishFlavor = new DishFlavor();
            if (flavor.getId() != null){
                dishFlavor.setId(flavor.getId());
            }
            dishFlavor.setDishId(dishId);
            dishFlavor.setName(flavor.getName());
            dishFlavor.setValue(flavor.getValue());
            dishFlavorService.save(dishFlavor);
        }
        return Result.success();
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Override
    public Result deleteDishInfoByIds(List<Long> ids) {
        // 判断是否有起售中的菜品
        for (Long id : ids) {
            Dish dish = this.getById(id);
            Integer status = dish.getStatus();
            if (!status.equals(StatusConstant.DISABLE)){
                throw new BaseException(DISH_ON_SALE);
            }
        }
        // 查看上是否有菜品被套餐使用
        for (Long id : ids) {
            Integer count = setmealDishService.lambdaQuery()
                    .eq(SetmealDish::getDishId, id)
                    .count();
            if (count > 0){
                throw new BaseException(DISH_BE_RELATED_BY_SETMEAL);
            }
        }
        // 批量删除
        this.removeByIds(ids);
        return Result.success();
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @Override
    public Result updateDishInfo(DishDTO dishDTO) {
        // 获取当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 获取当前菜品id
        Long dishId = dishDTO.getId();

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(userId);
        this.updateById(dish);

        // 更新口味
        // 删除原有口味
        dishFlavorService.removeById(dishId);
        for (DishFlavor flavor : dishDTO.getFlavors()) {
            DishFlavor dishFlavor = new DishFlavor();
            if (flavor.getId() != null){
                dishFlavor.setId(flavor.getId());
            }
            dishFlavor.setDishId(dishId);
            dishFlavor.setName(flavor.getName());
            dishFlavor.setValue(flavor.getValue());
            dishFlavorService.save(dishFlavor);
        }
        return Result.success();
    }

    /**
     * 根据id获取菜品信息
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> getDishInfoById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = this.getById(id);
        if (dish == null){
            throw new BaseException(DISH_NOT_EXIST);
        }
        BeanUtils.copyProperties(dish,dishVO);
        List<DishFlavor> flavorList = dishFlavorService.lambdaQuery()
                .eq(DishFlavor::getDishId, id)
                .list();
        String name = categoryService.lambdaQuery()
                .eq(Category::getId, dish.getCategoryId())
                .one()
                .getName();
        dishVO.setFlavors(flavorList);
        dishVO.setCategoryName(name);
        return Result.success(dishVO);
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public Result<List<Dish>> getDishListByCategoryId(Long categoryId) {
        List<Dish> dishList = this.lambdaQuery()
                .eq(Dish::getCategoryId, categoryId)
                .list();
        return Result.success(dishList);
    }

    /**
     * 菜品起售、停售
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result updateStatusById(Integer status, Long id) {
        // 判断是否有绑定的套餐未停售
        if(status.equals(StatusConstant.DISABLE)){
            List<SetmealDish> list = setmealDishService.lambdaQuery()
                    .eq(SetmealDish::getDishId, id)
                    .list();
            for (SetmealDish setmealDish : list) {
                Setmeal one = setmealService.lambdaQuery()
                        .eq(Setmeal::getId, setmealDish.getSetmealId())
                        .eq(Setmeal::getStatus, StatusConstant.ENABLE)
                        .one();
                if (one != null){
                    throw new BaseException(DISH_IS_USED);
                }
            }
        }

        this.lambdaUpdate()
                .set(Dish::getStatus, status)
                .eq(Dish::getId, id)
                .update();
        return Result.success();
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getAllList(dish);
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
